package com.bicon.botu.mall.member.api;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.bicon.botu.mall.member.entity.Cart;
import com.bicon.botu.core.base.common.Constants;
import com.bicon.botu.core.base.common.entity.BaseResult;
import com.bicon.botu.core.base.common.utils.JsonUtil;
import com.bicon.botu.core.base.common.utils.StringUtils;
import com.bicon.botu.mall.member.common.MemberConstants;
import com.bicon.botu.mall.member.dto.CartDto;
import com.bicon.botu.mall.member.dto.ProductDto;
import com.bicon.botu.mall.member.dto.ProductSkuDto;
import com.bicon.botu.mall.member.service.ICartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 购物车api
 *
 * @author 张露晨
 * @date 2017-07-19
 */
@RestController
@RequestMapping("/V1.0.0/api/cart")
public class CartApi {

    @Autowired
    private ICartService iCartService;


    /**
     * 添加商品至购物车
     *
     * @param userId        用户id
     * @param num           商品数量
     * @param productInfoId 商品信息id
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public BaseResult add(@RequestParam(value = "userId") String userId,
                          @RequestParam(value = "num") Integer num,
                          @RequestParam(value = "productInfoId") String productInfoId) {
        if (StringUtils.isAnyBlank(userId, productInfoId) || null == num) {
            return new BaseResult(Constants.RESPONSE_CODE_400, Constants.RESPONSE_MESSAGE_400);
        }
        String productState = iCartService.selectProductState(productInfoId);
        if (!MemberConstants.PRODUCT_UP_SHELVES.equals(productState)) {
            return new BaseResult(MemberConstants.RESPONSE_CODE_606, "商品已下架！");
        }
        //查询该商品是否被添加过
        Cart cart = new Cart().selectOne(new EntityWrapper<Cart>().eq("product_info_id", productInfoId).eq("user_id", userId));
        Integer productNum = iCartService.selectProductNum(productInfoId);
        //添加过则修改商品数量
        if (null != cart) {
            if (num + cart.getNum() >= productNum) {
                cart.setNum(productNum);
            } else {
                cart.setNum(num + cart.getNum());
            }
            cart.preUpdate();
            boolean result = iCartService.updateById(cart);
            if (!result) {
                return new BaseResult(Constants.RESPONSE_CODE_600, Constants.RESPONSE_MESSAGE_600);
            }
            return new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200);
        }
        //未添加过则新建记录
        cart = new Cart();
        cart.setUserId(userId);
        cart.setNum(num);
        cart.setProductInfoId(productInfoId);
        cart.preInsert();
        boolean result = cart.insert();
        if (!result) {
            return new BaseResult(Constants.RESPONSE_CODE_600, Constants.RESPONSE_MESSAGE_600);
        }
        return new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200);
    }

    /**
     * 查看购物车详情
     *
     * @param userId 用户id
     * @return
     */
    @RequestMapping(value = "/select", method = RequestMethod.POST)
    public BaseResult selectList(@RequestParam(value = "userId") String userId) {
        if (StringUtils.isAnyBlank(userId)) {
            return new BaseResult(Constants.RESPONSE_CODE_400, Constants.RESPONSE_MESSAGE_400);
        }
        List<Cart> cartList = iCartService.selectList(new EntityWrapper<Cart>().eq("user_id", userId));
        List<String> cartIdList = new ArrayList<String>();
        for (Cart cart : cartList) {
            cartIdList.add(cart.getId());
        }
        //根据用户id查询购物车详情
        List<CartDto> cartDtoList = iCartService.selectProduct(userId);
        cartDtoList.stream().forEach(cartDto -> cartDto.setLogisticsCenterDto(iCartService.selectLogisticsCenter(cartDto.getProductId())));
        //判断购物项是否可以购买
        for (CartDto cartDto : cartDtoList) {
            if (cartDto.getNum() > cartDto.getProductNum()) {
                cartDto.setState(MemberConstants.CART_STATE_NONE);
            } else {
                cartDto.setState(MemberConstants.CART_STATE_NORMAL);
            }
            //查询此类商品所有的规格
            List<ProductSkuDto> productSku = iCartService.selectProductSku(cartDto.getProductInfoId());
            cartDto.setProductSku(productSku);
            //删除下家商品
            Iterator it = cartIdList.iterator();
            while (it.hasNext()) {
                String str = (String) it.next();
                if (cartDto.getId().equals(str)) {
                    it.remove();
                }
            }
        }
        if (CollectionUtils.isEmpty(cartIdList)) {
            return new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200, cartDtoList);
        }
        boolean result = iCartService.deleteBatchIds(cartIdList);
        if (!result) {
            return new BaseResult(Constants.RESPONSE_CODE_600, Constants.RESPONSE_MESSAGE_600);
        }
        return new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200, cartDtoList);
    }

    /**
     * 修改购物车商品
     *
     * @param cartId        购物车对象id
     * @param num           商品数量
     * @param productInfoId 商品规格id
     * @return
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public BaseResult update(@RequestParam(value = "cartId") String cartId,
                             @RequestParam(value = "num") int num,
                             @RequestParam(value = "productInfoId", required = false) String productInfoId) {
        if (StringUtils.isBlank(cartId) || num <= 0) {
            return new BaseResult(Constants.RESPONSE_CODE_400, Constants.RESPONSE_MESSAGE_400);
        }
        int count = 200;
        if (num > count) {
            return new BaseResult(Constants.RESPONSE_CODE_400, "一次最多加入购物车200件");
        }
        Cart cart = new Cart();
        cart.setId(cartId);
        cart.setNum(num);
        cart.preUpdate();
        boolean b = cart.updateById();
        return b ? new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200) : new BaseResult(Constants.RESPONSE_CODE_500, "此购物车记录不存在");
    }

    /**
     * 删除商品
     *
     * @param cartIdJson 要删除的idJson
     * @return
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public BaseResult delete(@RequestParam(value = "cartIdJson") String cartIdJson) {
        ArrayList<String> cartIdList = JsonUtil.fromJson(cartIdJson, ArrayList.class);
        if (cartIdList.size() <= 0) {
            return new BaseResult(Constants.RESPONSE_CODE_400, Constants.RESPONSE_MESSAGE_400);
        }
        //将购物车的商品删除
        boolean result = iCartService.deleteBatchIds(cartIdList);
        if (!result) {
            return new BaseResult(Constants.RESPONSE_CODE_600, Constants.RESPONSE_MESSAGE_600);
        }
        return new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200);
    }


}

